# -*- coding: utf-8 -*-

import logging
import time

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext import search

import model
import minijson
import graph
from util import templated

class MainPage(webapp.RequestHandler):
    def _get_indexdata(self):
        req = model.Intake.gql(
            'WHERE user = :1 ORDER BY timestamp DESC', self.user).fetch(10)
        intakes = [(i.beverage.name,
                    time.asctime(time.gmtime(i.timestamp))) for i in req]

        return {
            'graph': graph.graph_url(self.user),
            'intakes': intakes
            }

    @templated('index.html')
    def get(self):
        if self.user:
            return self._get_indexdata()
        else:
            return {}

    @templated('index.html')
    def post(self):
        if self.user is None:
            self.redirect(self.request.uri)
            return

        # Handle form parameters.
        try:
            bev_id = int(self.request.get('bev-id'))
        except ValueError:
            return {'messsage': 'Invalid beverage selected'}

        bev = model.Beverage.get_by_id(bev_id)
        if not bev:
            return {'messsage': 'Invalid beverage selected'}

        intake = model.Intake(user=self.user, beverage=bev,
                              timestamp=time.time(),
                              caffeine_amount=bev.caffeine_amount)
        intake.put()

        data = self._get_indexdata()
        data['message'] = 'One %s consumed!' % bev.name
        return data

class BeverageSearch(webapp.RequestHandler):
    def post(self):
        query = self.request.get('q').decode('utf-8').lower()
        logging.info('beverage query: %s' % query)
        self.response.headers['Content-Type'] = 'application/json'

        qlen = len(query)
        if qlen < 3 or qlen > 20:
            return

        beverages = model.Beverage.all().search(query).order('name')
        best, other = [], []
        for beverage in beverages:
            data = {
                'name': beverage.name,
                'desc': '%s (%dmg)' % (beverage.name, beverage.caffeine_amount),
                'id': beverage.key().id()
                }
            if beverage.name[:qlen].lower() == query:
                best.append(data)
            else:
                other.append(data)
        self.response.out.write(minijson.write(best + other))
